package domain

import (
	"go-weixin/app/usercenter/model"
	"go-weixin/app/usercenter/rpc/internal/dao"
	"go-weixin/app/usercenter/rpc/internal/repo"
	"go-weixin/common/chendb"

	"github.com/zeromicro/x/errors"
)

type TableDomain struct {
	tableRepo repo.TableRepo
}

func NewTableDomain(engine chendb.ChenDb) *TableDomain {
	return &TableDomain{
		tableRepo: dao.NewTableDao(engine),
	}
}

func (t TableDomain) TableAdd(name string, url string, method int64) error {
	table := &model.TablesModel{}
	affected, err := t.tableRepo.TableAdd(name, url, method, table)
	if err != nil {
		return err
	}

	if affected == 0 {
		return errors.New(400, "添加表信息失败")
	}
	return nil
}

func (t TableDomain) TableExistByUrl(url string) error {
	has, err := t.tableRepo.TableExistByUrl(url)
	if err != nil {
		return err
	}

	if has {
		return errors.New(400, "该表地址已存在")
	}
	return nil
}

func (t TableDomain) TableList(page int64) ([]model.TablesModel, error) {
	tableList := make([]model.TablesModel, 0)
	limit := 10
	offset := 10 * (page - 1)
	err := t.tableRepo.TableList(int64(limit), offset, &tableList)
	if err != nil {
		return nil, err
	}
	return tableList, nil
}

func (t TableDomain) TableUpdateExist(id int64, url string) error {
	has, err := t.tableRepo.TableExistByUrl(url)
	if err != nil {
		return err
	}
	if has {
		return errors.New(400, "此Url已经被注册")
	}
	has, err = t.tableRepo.TableExistById(id)
	if err != nil {
		return err
	}
	if !has {
		return errors.New(400, "不存在的id")
	}
	return nil
}

func (t TableDomain) TableUpdate(id int64, name string, url string, method int64) error {
	affected, err := t.tableRepo.TableUpdate(id, name, url, method)
	if err != nil {
		return err
	}

	if affected == 0 {
		return errors.New(400, "修改table失败")
	}
	return nil
}
